<?php


namespace app\self\controller;


use app\admin\controller\Intermediary;
use app\business\module\Users;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;

class Extend    extends  Init
{


    /**
     * use   验证token是否正确
     * user  Hugh
     * date  2021/4/20 14:32
     */
    public function verificationToken()
    {
        $tokenUser = input('tokenUser');

        if(trim($tokenUser,'""') != $this->token)
        {
            return clearLoginInfo();
        }

    }


    /**
     * use  公共的渲染页面
     * by   hugh
     * time 2020/12/28 11:30
     */
    public function index()
    {
        $this->assign('title',$this->type);
        $module = $this->request->module(); //获取当前模板
        $controller = $this->request->controller(); //获取当前控制器
        $this->assign('getData',json_encode('/'.$module.'/'.$controller));
        $this->searchWhere();

        
        return view();
    }



    /**
     * use  获取数据
     * by   hugh
     * time 2020/12/28 13:50
     */
    public function data_list()
    {
        $limit = input('limit',15);
        $offset = input('offset',0);
        $tokenUser = input('tokenUser');
        if($tokenUser == $this->token)
        {
            session('MAP_USER', null);
            session_destroy();
            return json(['code'=>403,'msg'=>'登陆已过期,请重新登陆!']);
        }
        $sort = input('sort','id');
        $order = input('order','desc');
        //搜索的全部参数
        $search = input('search/a',[]);
        $map = $this->map($search); //默认的搜索条件

        $order = 'desc';
        $sort = 'a.id';
        $back = $this->data_list_search($map,$offset,$limit,$sort,$order);
        if($back !== 1)
        {
            return json(['rows'=>$back['data'],'total'=>$back['count']]);
        }
        //查询数据源
        $data   = DB::name($this->database)
            ->alias('a')
            ->where($map)
            ->limit($offset,$limit)
            ->order($sort,$order)
            ->select();
        //查询总数据的数量,用作分页
        $count  = DB::name($this->database)
            ->alias('a')
            ->where($map)
            ->order($sort,$order)
            ->count();
        //返回数据给接口
        return json(['rows'=>$data,'total'=>$count]);
    }

    public function data_list_search($map,$offset,$limit,$sort,$order)
    {
        return 1;
    }

    public function map($search)
    {
        $map = $this->mapSelf();

        foreach($search as $k =>$v)
        {
            if($v !== '0' && empty($v))continue; //如果值为空,则跳过
            //时间搜索和正常搜索 条件不一样,需要区分
            if(!in_array($k,['create_time','create_time_end','time','time_end']))
            {
                // 每个条件都是模糊查询,去除收尾空格
                $map['a.'.$k] = ['like','%'.trim($v).'%'];
            }
            else{
                if($k == 'create_time'){
                    if(empty($search['create_time_end']))
                    {
                        $map['a.create_time'] = [ '>=',$v.' 00:00:00'];
                    }
                    else{
                        $map['a.create_time'][0] = [ '>=',$v.' 00:00:00'];
                    }
                }

                if($k == 'create_time_end')
                {
                    if(empty($search['create_time']))
                    {
                        $map['a.create_time'] = ['<=',$v.' 23:59:59'];
                    }
                    else{
                        $map['a.create_time'][1] = ['<=',$v.' 23:59:59'];
                    }
                }

                if($k == 'time'){
                    if(empty($search['time_end']))
                    {
                        $map['a.time'] = [ '>=',$v.' 00:00:00'];
                    }
                    else{
                        $map['a.time'][0] = [ '>=',$v.' 00:00:00'];
                    }
                }

                if($k == 'time_end')
                {
                    if(empty($search['time']))
                    {
                        $map['a.time'] = ['<=',$v.' 23:59:59'];
                    }
                    else{
                        $map['a.time'][1] = ['<=',$v.' 23:59:59'];
                    }
                }
            }
        }

        return $map;
    }

    public function mapSelf()
    {
        return [];
    }







    /**
     * use  新增/修改
     * by   hugh
     * time 2020/12/29 10:31
     */
    public function edit()
    {

        if($this->request->isGet())
        {
            $edit = $this->getField();
            $this->assign('edit',$edit);
            $this->assign('editJS',json_encode($edit));
            return view();
        }
        elseif($this->request->isPost())
        {
            $data = input('data/a');
            $id = input('id/d',0);
            $where = $this->mapSelf();
            //重复验证
            $result = Db::name($this->database)
                ->where($data)
                ->where($where)
                ->where('id','<>',$id)
                ->find();
            if(!empty($result)) return duplication(); //数据重复
            $verification = $this->postVerification($data,$id); //数据验证
            if(!empty($verification)) return $verification;
            $type = $this->type;
            if($this->type == '合作伙伴') $data['type'] = '伙伴';
            $data['update_time'] = date('Y-m-d H:i:s');

            if(empty($id))
            {
                $data['create_time'] = date('Y-m-d H:i:s');

                DB::name($this->database)
                    ->insert($data);
                wlog($type,'新增数据',serialize($data));

            }
            else{
                DB::name($this->database)
                    ->where(['id'=>$id])
                    ->update($data);
                wlog($type,'编辑数据'.serialize($data),$id);
            }
            return success();
        }
    }



    public function postVerification($data,$id)
    {
        return '';
    }

    /**
     * use  删除
     * by   hugh
     * time 2020/12/29 10:32
     */
    public function del()
    {
        $tokenUser = input('tokenUser');
        if(trim($tokenUser,'"')  != $this->token) return clearLoginInfo();

        $ids = input('ids/a');
        DB::name($this->database)->where('id','in',$ids)->update(['is_delete'=>1]);
        wlog($this->type,'删除数据',serialize($ids));
        return success();
    }

    /**
     * use  启/禁用 两个状态之间来回切换
     * by   hugh
     * time 2020/12/29 14:42
     */
    public function disable()
    {
        $tokenUser = input('tokenUser');
        if(trim($tokenUser,'"')  != $this->token) return clearLoginInfo();

        $ids = input('ids/a');
        $ids = implode(',',$ids);
        $data = [
            'status'=>DB::raw('if(status = 0,1,0)'),
            'update_time'=>date('Y-m-d H:i:s'),
        ];
        DB::startTrans();
        try {
            DB::name($this->database)
                ->where('id','in',$ids)
                ->update($data);
            wlog($this->type,'禁用/启用数据',$ids);
            DB::commit();
        }catch(Exception $e)
        {
            DB::rollback();
            wlog($this->type,'禁用/启用失败,原因:'.$e->getMessage(),$ids);
        }
        return success();

    }


    /**
     * use   更改订单状态,状态更改为特定的值
     * user  Hugh
     * date  2021/3/17 14:26
     */
    public function changeOneField()
    {
        $tokenUser = input('tokenUser');

        if(trim($tokenUser,'"') != $this->token) return clearLoginInfo();

        $ids = input('ids/a');
        $status = input('status');
        $field = input('field');
        DB::startTrans();
        try {
            DB::name($this->database)
                ->where('id','in',$ids)
                ->update([$field=>$status]);
            wlog($this->type,'操作成功 ',serialize($ids));
            DB::commit();;
        }catch(\Exception $e)
        {
            DB::rollback();
            wlog($this->type,'操作失败 ',$e->getMessage());
        }
        return success();
    }





}